package com.wise.gemmes.controller.post;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.pojo.base.TSRole;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.core.util.MyBeanUtils;

import com.wise.gemmes.entity.post.PostEntity;
import com.wise.gemmes.entity.section.SectionEntity;
import com.wise.gemmes.entity.sectioncate.SectioncateEntity;
import com.wise.gemmes.service.post.PostServiceI;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.jeecgframework.core.beanvalidator.BeanValidators;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import java.io.IOException;
import java.net.URI;
import org.springframework.http.MediaType;
import org.springframework.web.util.UriComponentsBuilder;

/**   
 * @Title: Controller
 * @Description: 岗位信息
 * @author zhangdaihao
 * @date 2018-03-16 13:37:13
 * @version V1.0   
 *
 */
@Scope("prototype")
@Controller
@RequestMapping("/postController")
public class PostController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(PostController.class);

	@Autowired
	private PostServiceI postService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private Validator validator;
	
	private String message;
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	/**
	 * 岗位信息列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		return new ModelAndView("com/wise/gemmes/post/postList");
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(PostEntity post,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(PostEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, post, request.getParameterMap());
		this.postService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 删除岗位信息
	 * 
	 * @return
	 */
	@RequestMapping(params = "del")
	@ResponseBody
	public AjaxJson del(PostEntity post, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		post = systemService.getEntity(PostEntity.class, post.getId());
		message = "岗位信息删除成功";
		postService.delete(post);
		systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		
		j.setMsg(message);
		return j;
	}


	/**
	 * 添加岗位信息
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "save")
	@ResponseBody
	public AjaxJson save(PostEntity post, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		if (StringUtil.isNotEmpty(post.getId())) {
			message = "岗位信息更新成功";
			PostEntity t = postService.get(PostEntity.class, post.getId());
			try {
				MyBeanUtils.copyBeanNotNull2Bean(post, t);
				postService.saveOrUpdate(t);
				systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
			} catch (Exception e) {
				e.printStackTrace();
				message = "岗位信息更新失败";
			}
		} else {
			message = "岗位信息添加成功";
			postService.save(post);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}
		j.setMsg(message);
		return j;
	}
	

	/**
	 * 岗位信息列表页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "addorupdate")
	public ModelAndView addorupdate(PostEntity post, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(post.getId())) {
			post = postService.getEntity(PostEntity.class, post.getId());
			if(StringUtil.isNotEmpty(post.getSectionid())) {
				SectionEntity sectionEntity = postService.getEntity(SectionEntity.class, post.getSectionid());
				req.setAttribute("type", sectionEntity.getSectionCategory());
			}
			req.setAttribute("postPage", post);
		}
		return new ModelAndView("com/wise/gemmes/post/post_List");
	}
	
	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	public List<PostEntity> list() {
		List<PostEntity> listPosts=postService.getList(PostEntity.class);
		return listPosts;
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<?> get(@PathVariable("id") String id) {
		PostEntity task = postService.get(PostEntity.class, id);
		if (task == null) {
			return new ResponseEntity(HttpStatus.NOT_FOUND);
		}
		return new ResponseEntity(task, HttpStatus.OK);
	}

	@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public ResponseEntity<?> create(@RequestBody PostEntity post, UriComponentsBuilder uriBuilder) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<PostEntity>> failures = validator.validate(post);
		if (!failures.isEmpty()) {
			return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST);
		}

		//保存
		postService.save(post);

		//按照Restful风格约定，创建指向新任务的url, 也可以直接返回id或对象.
		String id = post.getId();
		URI uri = uriBuilder.path("/rest/postController/" + id).build().toUri();
		HttpHeaders headers = new HttpHeaders();
		headers.setLocation(uri);

		return new ResponseEntity(headers, HttpStatus.CREATED);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<?> update(@RequestBody PostEntity post) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<PostEntity>> failures = validator.validate(post);
		if (!failures.isEmpty()) {
			return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST);
		}

		//保存
		postService.saveOrUpdate(post);

		//按Restful约定，返回204状态码, 无内容. 也可以返回200状态码.
		return new ResponseEntity(HttpStatus.NO_CONTENT);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	@ResponseStatus(HttpStatus.NO_CONTENT)
	public void delete(@PathVariable("id") String id) {
		postService.deleteEntityById(PostEntity.class, id);
	}
	
	/**
	 * 选择用户界面
	 * */
	@RequestMapping(params = "users")
	public ModelAndView roles(HttpServletRequest request) {
		//--author：zhoujf-----start----date:20150531--------for: 编辑用户，选择角色,弹出的角色列表页面，默认没选中
		ModelAndView mv = new ModelAndView("com/wise/gemmes/post/users");
		String ids = oConvertUtils.getString(request.getParameter("ids"));
		mv.addObject("ids", ids);
		return mv;
		//--author：zhoujf-----end------date:20150531--------for: 编辑用户，选择角色,弹出的角色列表页面，默认没选中
	}
	
	/**
	 * 人员显示列表
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "datagridUser")
	public void datagridRole(TSUser tSUser, HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(TSUser.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tSUser);
		this.systemService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}
	
	/**
	 * 获取类别信息
	 * */
	@RequestMapping(params = "getJson")
	@ResponseBody
	public JSONArray getJson() {
		JSONArray jArray = new JSONArray();
		StringBuffer strb = new StringBuffer();
		for(int i=1;i<3;i++) {
			strb.append("{\"id\":");
			strb.append(i);
			strb.append(",\"text\":\"");
			strb.append("类别" + (i==1?"一":"二"));
			strb.append("\"}");
			jArray.add(strb.toString());
			strb.setLength(0);
		}
		return jArray;
	}
	
	/**
	 * 获取指定类别工段的信息
	 * */
	@RequestMapping(params = "setJson")
	@ResponseBody
	public JSONArray setJson(HttpServletRequest request) {
		JSONArray jArray = new JSONArray();
		String hql = "from SectionEntity s where sectionCategory = '" + request.getParameter("id") + "'";
		List<SectionEntity> list = systemService.findHql(hql);
		StringBuffer strb = new StringBuffer();
		for(SectionEntity s:list) {
			strb.append("{\"id\":");
			strb.append(s.getId());
			strb.append(",\"text\":\"");
			strb.append(s.getSectionName());
			strb.append("\"}");
			jArray.add(strb.toString());
			strb.setLength(0);
		}
		return jArray;
	}
	
	/**
	 * 页面加载时或类别改变时返回指定类别下信息
	 * */
	@RequestMapping(params = "getSec", produces = "application/json")
	public void getSec(HttpServletResponse response, HttpServletRequest request) throws IOException{
		String type = request.getParameter("type");
		String id = request.getParameter("id");
		
		StringBuffer strb = new StringBuffer();
		//type为空时，id不为空时，为查看或者修改，id为空时，为录入，type不为空时，为选择其他类别
		if(type.equals("")) {
			if(id.equals("")) {
				response.getWriter().write("{}");
				response.flushBuffer();
			}else {
				String sql = "select SECTION_CATEGORY from gem_section where id='" + id + "'";
				List<String> se = systemService.findListbySql(sql);
				for(String s:se) {
					type = s;
				}
				String hql = "from SectionEntity s where sectionCategory = '" + type + "'";
				List<SectionEntity> list = systemService.findHql(hql);
				//String str = "";
				JSONArray jsonArray = new JSONArray();
				for(SectionEntity sec:list) {
					
					strb.append("{\"id\":\"");
					strb.append(sec.getId());
					strb.append("\",\"name\":\"");
					strb.append(sec.getSectionName());
					strb.append("\"}");
					
					//str = "{\"id\":\"" + sec.getId() + "\",\"name\":\"" + sec.getSectionName() + "\"}";
					jsonArray.add(strb.toString());
					strb.setLength(0);
				}
				response.getWriter().write(jsonArray.toString());
				response.flushBuffer();
			}
			
		}else {
			String hql = "from SectionEntity s where sectionCategory = '" + type + "'";
			List<SectionEntity> list = systemService.findHql(hql);
			//String str = "";
			JSONArray jsonArray = new JSONArray();
			for(SectionEntity sec:list) {
				
				strb.append("{\"id\":\"");
				strb.append(sec.getId());
				strb.append("\",\"name\":\"");
				strb.append(sec.getSectionName());
				strb.append("\"}");
				
				//str = "{\"id\":\"" + sec.getId() + "\",\"name\":\"" + sec.getSectionName() + "\"}";
				jsonArray.add(strb.toString());
				strb.setLength(0);
			}
			response.getWriter().write(jsonArray.toString());
			response.flushBuffer();
		}
		
	}
	
	/**
	 * 页面加载时返回类别信息
	 * */
	@RequestMapping(params = "getSeccate", produces = "application/json")
	public void getSeccate(HttpServletResponse response, HttpServletRequest request) throws IOException{
		String id = request.getParameter("id");
		JSONArray jsonArray = new JSONArray();
		StringBuffer strb = new StringBuffer();
			String hql = "from SectioncateEntity s";
			List<SectioncateEntity> list = systemService.findHql(hql);
			for(SectioncateEntity se:list) {
				strb.append("{\"id\":\"");
				strb.append(se.getId());
				strb.append("\",\"name\":\"");
				strb.append(se.getName());
				strb.append("\",\"code\":\"");
				strb.append(se.getCode());
				strb.append("\"}");
				
				jsonArray.add(strb.toString());
				strb.setLength(0);
				
			}
		response.getWriter().write(jsonArray.toString());
		response.flushBuffer();
	}
}
